/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import React, { useCallback, useEffect, useState } from 'react';
import {
  View,
  Text,
  Image,
  StyleSheet,
  TouchableOpacity,
  FlatList,
  TextInput,
  Dimensions,
  ImageBackground,
  StatusBar,
} from 'react-native';
import {
  GridCol,
  GridRow,
  useBreakpointValue,
  NavigationSplitContainer,
  NavigationMode,
  NavBarPosition,
} from '@hadss/react_native_adaptive_layout';
import CustomTab from './components/CustomTab';
import debounce from 'lodash.debounce';
import TabButtom from './components/TabButtom';
import SwiperList from './components/SwiperList';
import VideoList from './components/VideoGrid';
import { ImageData, partImage } from './mock/index';

const App = (props: any) => {
  const { changePage } = props;
  const [currentBp, setCurrentBp] = useState<string>('unknown');
  const [text, setText] = useState<string>('');

  const BIGSCREEN = 1024;
  const MIDDLESCREEN = 768;
  const CONTANIERPADDING = 16;
  const ITEMGAP = 8;

  // 断点
  const onBreakpointChange = useCallback(
    debounce((bp: string) => {
      setCurrentBp(bp);
    }, 300),
    [],
  );

  const homeHeaderPointValue = useBreakpointValue({
    base: 40,
    sm: 40,
    md: 40,
    lg: 50,
    xl: 50,
  });
  const homeVideoPointValue = useBreakpointValue({
    base: 100,
    sm: 110,
    md: 140,
    lg: 150,
    xl: 150,
  });
  const homePartPointValue = useBreakpointValue({
    base: 38,
    sm: 38,
    md: 65,
    lg: 100,
    xl: 100,
  });

  const [screentViewWidth, setScreentViewWidth] = useState(
    Dimensions.get('window').width,
  );

  useEffect(() => {
    onGetListWidth();
    const subscription = Dimensions.addEventListener('change', () => {
      setScreentViewWidth(Dimensions.get('window').width);
    });
    return () => subscription.remove();
  }, [Dimensions.get('window').width]);

  // 定义断点
  const getColumns = () => {
    if (screentViewWidth >= BIGSCREEN) {
      return 4;
    }
    if (screentViewWidth >= MIDDLESCREEN) {
      return 3;
    } else {
      return 2;
    }
  };

  const onGetTab = (tab: number) => {
    return (
      (screentViewWidth -
        tab -
        2 * CONTANIERPADDING -
        (getColumns() - 1) * ITEMGAP) /
      getColumns()
    );
  };
  const [tabSpace, setTabSpace] = useState(0);

  const handleLayout = (event: any) => {
    const { width } = event.nativeEvent.layout;
    setTabSpace(width);
  };

  const onGetListWidth = () => {
    if (currentBp === 'lg' || currentBp === 'xl') {
      return onGetTab(tabSpace);
    } else {
      return onGetTab(0);
    }
  };
  const onGetListLeftSpace = (index: number) => {
    const columns = getColumns();
    const isFirstInRow = (index + 1) % columns === 1;
    return isFirstInRow ? 16 : ITEMGAP;
  };

  const onGetSpace = () => {
    if (currentBp === 'lg') {
      return '50%';
    } else if (currentBp === 'md') {
      return '60%';
    } else if (currentBp === 'sm') {
      return 65;
    } else if (currentBp === 'xs') {
      return 38;
    }
  };

  const noWrapHeaderComponent = (changePage: Function): React.ReactNode => {
    return (
      <View
        style={[styles.noWrapContainer, { paddingTop: homeHeaderPointValue }]}>
        <TouchableOpacity
          onPress={() => {
            changePage('Home');
          }}>
          <Image
            source={require('../../../assets/playList/back.png')}
            style={styles.backButton}
          />
        </TouchableOpacity>
        <View style={[styles.noWrapCustomContainer, { width: onGetSpace() }]}>
          <CustomTab />
        </View>
        <View style={styles.noWrapSearchContainer}>
          <View style={styles.noWrapSearchImage}>
            <Image
              style={styles.searchImage}
              source={require('../../../assets/pngs/search.png')}
            />
          </View>
          <TextInput
            placeholder="搜索..."
            onChangeText={text => setText(text)}
            value={text}
            style={styles.noWrapTextInput}
          />
          <View style={styles.noWrapClockImage}>
            <Image
              style={styles.bottomImg}
              source={require('../../../assets/pngs/clock.png')}
            />
          </View>
          <View style={styles.noWrapMoreImage}>
            <Image
              style={{ width: 14, height: 14 }}
              source={require('../../../assets/pngs/more.png')}
            />
          </View>
        </View>
      </View>
    );
  };

  const wrapHeaderComponent = (changePage: Function): React.ReactNode => {
    return (
      <>
        <View
          style={[styles.wrapContainer, { paddingTop: homeHeaderPointValue }]}>
          <TouchableOpacity
            onPress={() => {
              changePage('Home');
            }}>
            <Image
              source={require('../../../assets/playList/back.png')}
              style={styles.backButton}
            />
          </TouchableOpacity>
          <View style={styles.wrapCustomContainer}>
            <CustomTab />
          </View>
          <View style={styles.wrapMoreImage}>
            <Image
              style={{ width: 14, height: 14 }}
              source={require('../../../assets/pngs/more.png')}
            />
          </View>
        </View>
        <View style={[styles.inputContent]}>
          <View style={styles.wrapSearchImage}>
            <Image
              style={{ width: 16, height: 16 }}
              source={require('../../../assets/pngs/search.png')}
            />
          </View>
          <TextInput
            placeholder="搜索..."
            onChangeText={text => setText(text)}
            value={text}
            style={styles.wrapTextInput}
          />
          <View style={{ paddingLeft: 17 }}>
            <Image
              style={styles.bottomImg}
              source={require('../../../assets/pngs/clock.png')}
            />
          </View>
        </View>
      </>
    );
  };

  const partComponent = () => {
    return (
      <View style={{ marginVertical: 16 }}>
        <FlatList
          data={partImage}
          horizontal
          nestedScrollEnabled={true}
          keyExtractor={item => item.partId}
          showsHorizontalScrollIndicator={false}
          renderItem={({ item }: any) => (
            <TouchableOpacity
              style={[styles.partItem, { paddingRight: homePartPointValue }]}>
              <View style={styles.partItemImage}>
                <Image source={item.uri} style={{ width: 20, height: 20 }} />
              </View>
              <Text style={styles.partItemTitle}>{item.title}</Text>
            </TouchableOpacity>
          )}
        />
      </View>
    );
  };

  const filledData =
    ImageData.length % getColumns() === 0
      ? ImageData
      : [
        ...ImageData,
        ...Array(getColumns() - (ImageData.length % getColumns())).fill({
          isEmpty: true,
          id: 'empty',
        }),
      ];

  const renderItem = ({ item, index }: any) => (
    <View
      style={{
        width: onGetListWidth(),
        marginLeft: onGetListLeftSpace(index),
        marginRight: (index + 1) % getColumns() === 0 ? 16 : 0,
        overflow: 'hidden',
        marginBottom: 10,
        flex: 1,
      }}>
      <View style={{ height: homeVideoPointValue }}>
        <ImageBackground
          source={item.url}
          style={[styles.backgroundImage, { width: onGetListWidth() }]}
          resizeMode="cover">
          {item.isFilm && (
            <View style={styles.filmItem}>
              <Text style={styles.filmItemTitle}>正片</Text>
            </View>
          )}
          {item.score && (
            <View style={styles.scoreItem}>
              <Text style={styles.scoreItemTitle}>{item.score}</Text>
            </View>
          )}
        </ImageBackground>
      </View>
      <Text numberOfLines={1} ellipsizeMode="tail" style={styles.titleItem}>
        {item.title}
      </Text>
      <Text
        numberOfLines={1}
        ellipsizeMode="tail"
        style={styles.descriptionItem}>
        {item.description}
      </Text>
    </View>
  );
  const changeHeight = useBreakpointValue({
    base: 200,
    sm: 200,
    md: 220,
    lg: 240,
    xl: 250,
  });

  const HomeScreen = () => {
    return (
      <View style={{ flex: 1, backgroundColor: '#fff' }}>
        <GridRow
          onBreakpointChange={onBreakpointChange}
          style={styles.gridRow}
          columns={12}>
          {/* 大屏侧边栏 */}
          {currentBp === 'lg' && (
            <GridCol
              span={{ xs: 0, sm: 0, md: 0, lg: 1 }}
              offset={0}
              order={0}
              onLayout={handleLayout}>
              <TabButtom currentBp={currentBp} type={1} />
            </GridCol>
          )}
          {/* 消息列表页 */}
          {(currentBp === 'sm' ||
            currentBp === 'md' ||
            currentBp === 'xs' ||
            currentBp === 'lg') && (
              <GridCol
                span={{ xs: 12, sm: 12, md: 12, lg: 11 }}
                offset={0}
                order={0}>
                {/* 顶部搜索 */}
                {(currentBp === 'md' || currentBp === 'lg') &&
                  noWrapHeaderComponent(changePage)}
                {(currentBp === 'sm' || currentBp === 'xs') &&
                  wrapHeaderComponent(changePage)}
                {/* 滚动 */}
                <FlatList
                  data={filledData}
                  numColumns={getColumns()}
                  key={`columns-${getColumns()}`}
                  contentContainerStyle={{
                    justifyContent: 'flex-start', // 自动均匀分布
                  }}
                  showsVerticalScrollIndicator={false}
                  ListHeaderComponent={
                    <View style={{ width: '100%' }}>
                      <View
                        style={{
                          height: changeHeight,
                          paddingHorizontal: 16,
                          borderRadius: 20,
                          overflow: 'hidden',
                        }}>
                        {(currentBp == 'sm' || currentBp === 'xs') && (
                          <SwiperList />
                        )}
                        {(currentBp == 'md' || currentBp === 'lg') && (
                          <VideoList />
                        )}
                      </View>
                      {partComponent()}
                    </View>
                  }
                  keyExtractor={item => item.id.toString()}
                  renderItem={renderItem}
                />

                {/* Bottom */}
                {(currentBp == 'sm' ||
                  currentBp == 'md' ||
                  currentBp == 'xs') && (
                    <TabButtom currentBp={currentBp} type={2} />
                  )}
              </GridCol>
            )}
        </GridRow>
      </View>
    );
  };
  return (
    <>
      <StatusBar backgroundColor={'#FFFFFF'} barStyle="dark-content" />
      <NavigationSplitContainer
        mode={NavigationMode.Stack}
        navBarPosition={NavBarPosition.Start}
        navBarWidth={400}
        navBarWidthRange={[240, 400]}
        minContentWidth={200}>
        <HomeScreen />
      </NavigationSplitContainer>
    </>
  );
};

const styles = StyleSheet.create({
  gridRow: {
    flex: 1,
  },
  backButton: {
    width: 40,
    height: 40,
    marginRight: 16,
  },
  inputContent: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    height: 60,
    paddingHorizontal: 16,
    paddingVertical: 16,
  },
  bottomWrap: {
    flexDirection: 'row',
    backgroundColor: 'rgba(241, 243, 245, 0.8)',
    paddingVertical: 10,
    paddingBottom: 28,
    zIndex: 11,
  },
  bottomWrapLg: {
    flexDirection: 'column',
    width: 96,
    height: '100%',
    backgroundColor: 'rgba(241, 243, 245, 0.8)',
    alignItems: 'center',
    justifyContent: 'center',
    zIndex: 11,
  },
  bottomImg: {
    width: 24,
    height: 24,
  },
  noWrapContainer: {
    width: '100%',
    flexDirection: 'row',
    paddingHorizontal: 16,
    paddingVertical: 16,
    alignItems: 'center',
    justifyContent: 'center',
  },
  noWrapCustomContainer: {
    height: 40,
    overflow: 'hidden',
    marginRight: 16,
    alignItems: 'center',
  },
  noWrapSearchContainer: {
    flex: 1,
    flexDirection: 'row',
    zIndex: 10,
  },
  noWrapSearchImage: {
    position: 'absolute',
    top: 12,
    zIndex: 1,
    left: 12,
  },
  noWrapTextInput: {
    flex: 1,
    borderRadius: 20,
    height: 40,
    backgroundColor: 'rgba(0, 0, 0, 0.05)',
    paddingLeft: 30,
  },
  noWrapClockImage: {
    marginLeft: 16,
    justifyContent: 'center',
    alignItems: 'center',
    width: 40,
    height: 40,
    borderRadius: 40,
    backgroundColor: 'rgba(0, 0, 0, 0.05)',
  },
  noWrapMoreImage: {
    justifyContent: 'center',
    alignItems: 'center',
    width: 40,
    height: 40,
    borderRadius: 40,
    backgroundColor: 'rgba(0, 0, 0, 0.05)',
    marginLeft: 8,
  },
  wrapContainer: {
    flexDirection: 'row',
    paddingHorizontal: 16,
    paddingBottom: 8,
  },
  wrapCustomContainer: {
    flex: 1,
    overflow: 'hidden',
    marginRight: 16,
  },
  wrapMoreImage: {
    justifyContent: 'center',
    alignItems: 'center',
    width: 40,
    height: 40,
    borderRadius: 40,
    backgroundColor: 'rgba(0, 0, 0, 0.05)',
  },
  wrapSearchImage: {
    position: 'absolute',
    top: 22,
    zIndex: 1,
    left: 30,
  },
  wrapTextInput: {
    flex: 1,
    borderRadius: 20,
    height: 40,
    backgroundColor: 'rgba(0, 0, 0, 0.05)',
    paddingLeft: 34,
  },
  searchImage: {
    width: 16,
    height: 16,
  },
  partItem: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingLeft: 16,
  },
  partItemImage: {
    width: 40,
    height: 40,
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: 40,
    backgroundColor: '#f8e6da',
    marginBottom: 6,
  },
  partItemTitle: {
    fontSize: 12,
    textAlign: 'center',
  },
  backgroundImage: {
    flex: 1,
    height: 150,
    borderRadius: 15,
    overflow: 'hidden',
  },
  filmItem: {
    width: 50,
    height: 20,
    backgroundColor: '#ff8c1a',
    borderBottomRightRadius: 25,
  },
  filmItemTitle: {
    fontSize: 12,
    textAlign: 'center',
    color: '#ffffff',
    lineHeight: 20,
  },
  scoreItem: {
    position: 'absolute',
    bottom: 5,
    right: 8,
    width: 30,
    height: 20,
    backgroundColor: '#979da6',
    borderRadius: 6,
  },
  scoreItemTitle: {
    fontSize: 12,
    textAlign: 'center',
    color: '#ffffff',
    lineHeight: 20,
  },
  titleItem: {
    marginTop: 4,
    fontWeight: 'bold',
    fontSize: 14,
  },
  descriptionItem: {
    marginTop: 4,
    fontWeight: 'normal',
    fontSize: 12,
  },
});

export default App;
